package com.feihao.zhou.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //私有构造方法：
    private JDBCUtils() {
    }

    //声明所需的配置变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    //提供静态代码快
    static {
        try {
            System.out.println("注册驱动执行了");
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties pro = new Properties();
            pro.load(is);

            driverClass = pro.getProperty("driverClass");
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            password = pro.getProperty("password");

            //注册驱动：
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //提供静态获取数据库连接的方法

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    //提供静态释放连接的方法：

    public static void close(ResultSet re, PreparedStatement preparedStatement, Connection connection) {
        if (re != null) {
            try {
                re.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    //增删改的操作执行的释放资源方法
    public static void close(PreparedStatement preparedStatement, Connection connection) {

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
